package plgbasev0

import (
	"dgo/goutils/utils"
	"fmt"
	"time"
)

/*
**

	Interval
*/
type InnerInterval struct {
	objdna      uint32
	interval    time.Duration
	intervalDNA int
	ReleaseFlag int
	OnStartFunc func()
	OnStopFunc  func()
}

func NewInnerInterval() *InnerInterval {
	return &InnerInterval{}
}

func (this *InnerInterval) checkDNA() uint32 {
	if this.objdna == 0 {
		this.objdna = utils.NewObjectDNA()
	}
	return this.objdna
}

func (this *InnerInterval) Release() {
	this.ReleaseFlag = 1
	if this.OnStopFunc != nil {
		this.OnStopFunc()
	}
}

func (this *InnerInterval) CheckReload(interval time.Duration, fn func()) (changed bool) {
	if this.interval != interval {
		this.intervalDNA++
		if interval <= 0 { // 传入0 进行关闭
			if this.OnStopFunc != nil {
				this.OnStopFunc()
			}
			this.interval = 0
			return true
		}

		if this.interval <= 0 { // 之前是关闭的, 现在进行开启
			if this.OnStartFunc != nil {
				this.OnStartFunc()
			}
		}
		this.interval = interval
		dna := this.intervalDNA
		this.checkDNA()
		utils.AddTaskFxiedInterval(fmt.Sprintf("obj_%d", this.objdna),
			this.interval, func() bool {
				if dna != this.intervalDNA || this.ReleaseFlag == 1 {
					return false
				}
				if fn != nil {
					fn()
				}
				return true
			})

		changed = true

	} else {
		changed = false
	}
	return
}
